import React, {useEffect, useState} from "react";
import {Form, FormInstance, Modal, Select, Switch, Tree, TreeDataNode, TreeProps} from "antd";
import {getFetch, postFetch} from "@/app/lib/HttpProtocol";

const apis = {
	positionListApi:'/position/page/available',
	deptTreeApi:'/corp/dept/tree/available'
}

function toSelectOptions(corpList: any[]) {
	return corpList.map(c => {
		return {value:c.id,label:c.name};
	});
}

// @ts-ignore
function getDeptTitle(t: any,workDeptIds,checkedDeptIds,onWorkDeptSwitchChange) {
	return (
		<span style={{alignItems:"center",display:"flex",}}>
			<label>{t.name}</label>&emsp;
			<Switch checkedChildren="管理员"
							unCheckedChildren={"管理员"}
							size={"small"}
							key={t.id}
							onChange={(checked) => onWorkDeptSwitchChange(checked,t.id)}
							checked={checkedDeptIds.includes(t.id)}
							disabled={!workDeptIds.includes(t.id)}/>
		</span>
	)
}

// @ts-ignore
function toTreeData(deptTrees:any[],workDeptIds:string[],checkedDeptIds:string[],onWorkDeptSwitchChange) : TreeDataNode[]|undefined {
	if(deptTrees == undefined){
		return [];
	}
	return deptTrees.map(t => {
		return {title:getDeptTitle(t,workDeptIds,checkedDeptIds,onWorkDeptSwitchChange),key:t.id,disabled:t.disabled == 1,children:toTreeData(t.children,workDeptIds,checkedDeptIds,onWorkDeptSwitchChange)}
	})
}

function setWorkDepts(form:FormInstance<any>,workDeptIds: any[], managerIds: any[]) {
	if(workDeptIds.length == 0){
		form.setFieldValue("depts",[]);
		return;
	}
	form.setFieldValue("depts",workDeptIds.map(deptId => {
		if(managerIds.includes(deptId)){
			return {id:deptId,manager:1};
		}else{
			return {id:deptId,manager:0};
		}
	}))
}

// @ts-ignore
function WorkEditForm({onFormInstanceReady,corpList}){
	const [form] = Form.useForm();
	const [positionList,setPositionList] = useState<any[]>([])
	const [deptTrees,setDeptTrees] = useState<any[]>([])
// @ts-ignore
	const [workDeptIds,setWorkDeptIds] = useState<any[]>([])
// @ts-ignore
	const [managerIds,setManagerIds] = useState<any[]>([])
	function onSwitchChange(checked:boolean,deptId:string){
		let currentManagerIds = [...managerIds];
		if(checked) {
			if (!currentManagerIds.includes(deptId)) {
				currentManagerIds.push(deptId)
			}
		}else{
			currentManagerIds = currentManagerIds.filter(id => id != deptId);
		}
		setManagerIds(currentManagerIds);
		setWorkDepts(form,workDeptIds,currentManagerIds);
	}
	useEffect(() => {
		onFormInstanceReady(form);
	}, []);
	function handleCorpChange(value:string){
		postFetch(apis.positionListApi,{corpId:value}).then(page => {
			// @ts-ignore
			setPositionList(page.list)
			form.setFieldValue('positionId',null)
		})
		getFetch(apis.deptTreeApi,{corpId:value}).then(data => {
// @ts-ignore
			setDeptTrees(data);
		})
		setWorkDepts(form,[],[])
	}
	
	const onCheck: TreeProps['onCheck'] = (checkedKeys) => {
// @ts-ignore
		const currentWorkDeptIds = checkedKeys.checked ;
		setWorkDeptIds(currentWorkDeptIds)
		setWorkDepts(form,currentWorkDeptIds,managerIds);
	};
	return(
		<Form layout={"horizontal"} form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 12 }} size={"small"} >
			<Form.Item
				name="corpId"
				label="公司"
			>
				<Select
					showSearch
					style={{ width: 200 }}
					placeholder="Search to Select"
					optionFilterProp="children"
					filterOption={(input, option) => (option?.label ?? '').includes(input)}
					filterSort={(optionA, optionB) =>
						(optionA?.label ?? '').toLowerCase().localeCompare((optionB?.label ?? '').toLowerCase())
					}
					onChange={handleCorpChange}
					options={toSelectOptions(corpList)}
				/>
			</Form.Item>
			<Form.Item name={"positionId"} label={"职位"} >
				<Select
					showSearch
					style={{ width: 200 }}
					placeholder="Search to Select"
					optionFilterProp="children"
					filterOption={(input, option) => (option?.label ?? '').includes(input)}
					filterSort={(optionA, optionB) =>
						(optionA?.label ?? '').toLowerCase().localeCompare((optionB?.label ?? '').toLowerCase())
					}
					options={toSelectOptions(positionList)}
				/>
			</Form.Item>
			<Form.Item name="primary" label={"默认"} >
				<Switch />
			</Form.Item>
			<Form.Item name="depts" label={"部门"} >
				<Tree
					checkable
					defaultExpandedKeys={workDeptIds}
					defaultSelectedKeys={workDeptIds}
					defaultCheckedKeys={workDeptIds}
					onCheck={onCheck}
					treeData={toTreeData(deptTrees,workDeptIds,managerIds,onSwitchChange)}
					checkStrictly={true}
				/>
			</Form.Item>
		</Form>
	)
}
// @ts-ignore
export default function WorkAddModal({open,onAddOk,onCancel,corpList}){
	const [formInstance, setFormInstance] = useState<FormInstance>();
	useEffect(() => {
		if(corpList == null){
		}
	}, []);
	return(
		<>
			<Modal
				open={open}
				title="编辑"
				okText="确定"
				cancelText="取消"
				okButtonProps={{ autoFocus: true }}
				onCancel={onCancel}
				destroyOnClose
				onOk={async () => {
					try {
						const values = await formInstance?.validateFields();
						formInstance?.resetFields();
						onAddOk(values);
					} catch (error) {
						console.log('Failed:', error);
					}
				}}
			>
				<WorkEditForm
					// @ts-ignore
					onFormInstanceReady={(instance) => {
						setFormInstance(instance);
					}}
					corpList={corpList}
				/>
			</Modal>
		</>
	);
}